package cn.chiship.sdk.core.properties;

import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import cn.chiship.sdk.core.util.PropertiesFileUtil;
import cn.chiship.sdk.core.util.StringUtil;

import java.util.MissingResourceException;

/**
 * 常量配置
 *
 * @author LiJian
 */
public class CommonConfigProperties {

	private String prefix = "chiship.";

	private static CommonConfigProperties instance;

	private static PropertiesFileUtil propertiesFileUtil;

	private CommonConfigProperties() {

	}

	public static synchronized CommonConfigProperties getInstance() {
		return getInstance("application");
	}

	public static synchronized CommonConfigProperties getInstance(String propertiesName) {
		if (null == instance) {
			instance = new CommonConfigProperties();
			loadProperties(propertiesName);
		}
		return instance;
	}

	private static void loadProperties(String name) {
		try {
			propertiesFileUtil = PropertiesFileUtil.getInstance(name);
		}
		catch (MissingResourceException e) {
			throw new SystemErrorException("兄弟,请确保'" + name + ".properties'文件存在!");
		}
	}

	/**
	 * 根据Key值获得对应数值 example chiship.demo.version key=demo.version chiship.为属性文件前缀
	 * @param key
	 * @return 结果
	 */
	public String getValue(String key) {
		return getValue(key, null);
	}

	/**
	 * 根据Key值获得对应数值 example chiship.demo.version key=demo.version chiship.为属性文件前缀
	 * @param key
	 * @param defaultValue
	 * @return 结果
	 */
	public String getValue(String key, String defaultValue) {
		if (!StringUtil.isNullOrEmpty(defaultValue)) {
			return defaultValue;
		}
		String value = propertiesFileUtil.get(prefix + key);
		if (StringUtil.isNullOrEmpty(value)) {
			throw new SystemErrorException("无效或缺少属性Key:[" + prefix + key + "]");
		}
		return value;
	}

}
